package com.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;

public class MyConfigCenter implements Watcher {

    private final String CONNECT_ADDRESS = "192.168.1.120";
    private final Integer SESSIONT_IMEOUT = 5 * 1000;
    private static ZooKeeper zk;
    private String username;
    private String password;
    private String url;
    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public MyConfigCenter() {
        initMyConfig();
    }

    public void process(WatchedEvent event) {
        //连接成功时
        if (Event.KeeperState.SyncConnected == event.getState()) {
            System.out.println("连接成功");
            countDownLatch.countDown();
            //节点数据发生变更时
            if (Event.EventType.NodeDataChanged == event.getType()) {
                initMyConfig();
            }
        }
    }

    public void initMyConfig() {
        try {
            zk = new ZooKeeper(CONNECT_ADDRESS, SESSIONT_IMEOUT, this);
            countDownLatch.await();
            username = new String(zk.getData("/Conf/username", true, null));
            password = new String(zk.getData("/Conf/password", true, null));
            url = new String(zk.getData("/Conf/url", true, null));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyConfigCenter myConfigCenter = new MyConfigCenter();
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(5 * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("第" + (i+1) + "次监测");
            System.out.println(myConfigCenter.getUsername());
            System.out.println(myConfigCenter.getPassword());
            System.out.println(myConfigCenter.getUrl());
        }
    }


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

}
